import React, { PureComponent, Fragment } from 'react';

import { Row, Col, Checkbox, Button, Icon, Select, Form, TreeSelect } from 'antd';
import AuthorizedButton from '@/components/AuthorizedButton';

import { connect } from 'dva';
import router from 'umi/router';
import _ from 'lodash';
import * as utils from '../../utils/treeUtils';
import * as apis from '@/services/SupplyPlanMgr';

const FormItem = Form.Item;
const { Option } = Select;

@connect(state => ({
  searchItems: state.SupplyPlanDetailItems.searchItems,
  overAllYears: state.SupplyPlanDetailItemsYears.overAllYears,
  currentYear: state.SupplyPlanDetailItemsYears.currentYear,
  currentMonths: state.SupplyPlanDetailItemsYears.currentMonths,
  all: state.SupplyPlanDetailItems.all,
}))
@Form.create()
export default class PageTop extends PureComponent {
  state = {
    expandForm: false,
    attributes: [
      { label: '金额', value: '金额' },
      { label: '面积', value: '面积' },
      { label: '套数', value: '套数' },
      { label: '均价', value: '均价' },
    ],
    attributes1: [
      { label: '供货计划', value: '供货计划' },
      { label: '供货实际', value: '供货实际' },
      { label: '供货达成率', value: '供货达成率' },
    ],
    stage: '',
    group: '',
    productType: '',
    product: '',
    build: '',
  };

  componentWillReceiveProps(nextProps) {
    // match变动
    if (
      this.props.match.params.project !== nextProps.match.params.project &&
      nextProps.match.params.project
    ) {
      this.handleFormReset();
    }
  }

  /**
   * @description: 确认供货
   * @param {type}
   * @return
   */
  handleOkSupplyClick = () => {
    // _paq.push(['trackEvent', 'appClick', '<appName>','点击应用' ]);
    const { project, level1, level2 } = this.props.match.params;
    // todo 调用接口
    const { match } = this.props;
    const params = {
      projectId: match.params.project,
    };
    apis.isNeedSpplyConfirmUsingGET({ params }).then(result => {
      if (result.data) {
        router.replace(`/OperatingPlan/SupplyPlan/ConfirmProject/${level1}/${level2}/${project}`);
      }
    });
  };

  // 根据查询条件搜索
  handleSearch = e => {
    const self = this;
    e.preventDefault();
    const { dispatch, form, currentYear, match } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = _.values(
        _.mapValues(fieldsValue, value =>
          value ? value.split('|')[1].replace(/\(.*\)/, '') : 'null',
        ),
      ).join('/');
      this.props.setCode(values);
      this.props.getItems(this.props, match.params.project, values);
    });
  };

  // 重置查询条件
  handleFormReset = () => {
    const { form, match } = this.props;
    form.resetFields();
    this.props.setCode('');
    this.setState({
      stage: '',
      group: '',
      productType: '',
      product: '',
      build: '',
    });
    // this.props.getItems(this.props, currentYear, match.params.project);
  };

  // 切换搜索条件的展示方式
  toggleForm = () => {
    const self = this;
    this.setState({
      expandForm: !self.state.expandForm,
    });
    this.props.expandForm(!self.state.expandForm);
  };

  // 搜索条件的展示方式———展开
  renderAdvancedForm = () => {
    const formItemLayout = {
      labelCol: { span: 8 },
      wrapperCol: { span: 16 },
      style: { marginBottom: 0 },
    };
    const { getFieldDecorator, setFieldsValue } = this.props.form;
    const { searchItems } = this.props;
    const { stage, group, productType, product } = this.state;

    // 组团
    let groups = [];
    let products = [];
    let productTypes = [];
    let builds = [];
    // 分期
    const stages = utils.getSearchTypeItems(searchItems.org_stage, 'name', 'id');
    // 组团
    groups = utils.getSearchTypeItems(searchItems.org_group, 'name', 'id');
    // 业态
    products = utils.getSearchTypeItems(searchItems.org_product, 'name', 'id');
    // 产品构成
    productTypes = utils.getSearchTypeItems(
      searchItems.org_product,
      'proProductName',
      'proProductCode',
    );
    // 楼栋
    builds = utils.getSearchTypeItems(searchItems.org_build, 'name', 'id');
    if (stage) {
      const orgStage = _.filter(searchItems.org_stage, { id: stage });
      groups = utils.getSearchSeltetItems(orgStage, 'org_group', 'name', 'id');
      products = utils.getSearchSeltetItems(orgStage, 'org_product', 'name', 'id');
      productTypes = utils.getSearchSeltetItems(
        orgStage,
        'org_product',
        'proProductName',
        'proProductCode',
      );
      builds = utils.getSearchSeltetItems(orgStage, 'org_build', 'name', 'id');
    }
    if (group) {
      let orgStage = [];
      // 有分期 取当前分期下组团所有业态产品构成 否 取所有分期组团下所有业态产品构成
      orgStage = _.filter(searchItems.org_group, { id: group });
      let allGroup = [];
      allGroup = utils.buildChildren(allGroup, searchItems.org_stage, 'org_group');
      if (!stage) {
        orgStage = _.filter(allGroup, { name: orgStage[0].name });
      }
      products = utils.getSearchSeltetItems(orgStage, 'org_product', 'name', 'id');
      productTypes = utils.getSearchSeltetItems(
        orgStage,
        'org_product',
        'proProductName',
        'proProductCode',
      );
      builds = utils.getSearchSeltetItems(orgStage, 'org_build', 'name', 'id');
    }

    if (productType) {
      let orgProduct = [];
      let orgStage = [];
      if (group) {
        const orgGroup = _.filter(searchItems.org_group, { id: group });
        orgProduct = orgGroup[0].children;
      } else if (stage) {
        orgStage = _.filter(searchItems.org_stage, { id: stage });
        const allGroup = [];
        orgProduct = utils.buildChildren(allGroup, orgStage, 'org_product');
      } else {
        orgProduct = searchItems.org_product;
      }
      orgStage = _.filter(orgProduct, { proProductCode: productType });
      products = utils.getSearchSeltetItems(orgStage, 'org_product', 'name', 'id');
      builds = utils.getSearchSeltetItems(orgStage, 'org_build', 'name', 'id');
    }
    if (product) {
      let orgProduct = [];
      let orgStage = [];
      if (group) {
        const orgGroup = _.filter(searchItems.org_group, { id: group });
        orgProduct = orgGroup[0].children;
      } else if (stage) {
        orgStage = _.filter(searchItems.org_stage, { id: stage });
        const allGroup = [];
        orgProduct = utils.buildChildren(allGroup, orgStage, 'org_product');
      } else {
        orgProduct = searchItems.org_product;
      }
      if (group === '' && stage === '') {
        const productName = _.filter(searchItems.org_product, { id: product });
        orgProduct = _.filter(searchItems.org_product, { name: productName[0].name });
      } else {
        orgProduct = _.filter(orgProduct, { id: product });
      }
      builds = utils.getSearchSeltetItems(orgProduct, 'org_build', 'name', 'id');
    }

    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row type="flex" justify="center" align="middle">
          <Col md={20} sm={24}>
            <FormItem label="分期">
              {getFieldDecorator('stage', {
                // initialValue: '',
              })(
                <Select
                  dropdownMatchSelectWidth={false}
                  size="small"
                  style={{ width: 125 }}
                  onChange={value => {
                    setFieldsValue({ group: '', productType: '', product: '', build: '' });
                    this.setState({
                      stage: value.split('|')[0],
                      group: '',
                      productType: '',
                      product: '',
                      // build: '',
                    });
                  }}
                  placeholder="全部"
                >
                  <Option value="">全部</Option>
                  {stages &&
                    stages.length > 0 &&
                    stages.map(value => (
                      <Option key={value.code} value={`${value.code}|${value.name}`}>
                        {value.name.replace(/\(.*\)/, '') || '暂无名称'}
                      </Option>
                    ))}
                </Select>,
              )}
            </FormItem>
            <FormItem label="组团">
              {getFieldDecorator('group', {
                // initialValue: '',
              })(
                <Select
                  dropdownMatchSelectWidth={false}
                  size="small"
                  style={{ width: 125 }}
                  onChange={value => {
                    setFieldsValue({ productType: '', product: '', build: '' });
                    this.setState({
                      group: value.split('|')[0],
                      productType: '',
                      product: '',
                      // build: '',
                    });
                  }}
                  placeholder="全部"
                >
                  <Option value="">全部</Option>
                  {groups &&
                    groups.length > 0 &&
                    groups.map(value => (
                      <Option key={value.code} value={`${value.code}|${value.name}`}>
                        {value.name || '暂无名称'}
                      </Option>
                    ))}
                </Select>,
              )}
            </FormItem>
            <FormItem label="业态">
              {getFieldDecorator('productType', {
                // initialValue: '',
              })(
                <Select
                  dropdownMatchSelectWidth={false}
                  size="small"
                  style={{ width: 125 }}
                  onChange={value => {
                    setFieldsValue({ product: '', build: '' });
                    this.setState({
                      productType: value.split('|')[0],
                      product: '',
                      // build: '',
                    });
                  }}
                  placeholder="全部"
                >
                  <Option value="">全部</Option>
                  {productTypes &&
                    productTypes.length > 0 &&
                    productTypes.map(value => (
                      <Option key={value.code} value={`${value.code}|${value.name}`}>
                        {value.name || '暂无名称'}
                      </Option>
                    ))}
                </Select>,
              )}
            </FormItem>
            <FormItem label="产品构成">
              {getFieldDecorator('product', {
                // initialValue: '',
              })(
                <Select
                  dropdownMatchSelectWidth={false}
                  size="small"
                  style={{ width: 125 }}
                  onChange={value => {
                    setFieldsValue({ build: '' });
                    this.setState({
                      product: value.split('|')[0],
                      // build: '',
                    });
                  }}
                  placeholder="全部"
                >
                  <Option value="">全部</Option>
                  {products &&
                    products.length > 0 &&
                    products.map(value => (
                      <Option key={value.code} value={`${value.code}|${value.name}`}>
                        {value.name || '暂无名称'}
                      </Option>
                    ))}
                </Select>,
              )}
            </FormItem>
            <FormItem label="楼栋">
              {getFieldDecorator('build', {
                // initialValue: '',
              })(
                <Select size="small" style={{ width: 125 }} placeholder="全部">
                  <Option value="">全部</Option>
                  {builds &&
                    builds.length > 0 &&
                    builds.map(value => (
                      <Option key={value.code} value={`${value.code}|${value.name}`}>
                        {value.name || '暂无名称'}
                      </Option>
                    ))}
                </Select>,
              )}
            </FormItem>
          </Col>
          <Col md={3} sm={24} justify="space-around" align="middle">
            <Button type="primary" htmlType="submit">
              查询
            </Button>
            <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
              重置
            </Button>
          </Col>
        </Row>
      </Form>
    );
  };

  changeCurrentMonths = value => {
    const { match, dispatch } = this.props;
    const self = this;
    dispatch({
      type: 'SupplyPlanDetailItemsYears/changeCurrentMonths',
      payload: {
        currentMonths: value,
      },
    });
  };

  changeCurrentYear(value) {
    const { match, dispatch } = this.props;
    const self = this;
    dispatch({
      type: 'SupplyPlanDetailItemsYears/changeCurrentYear',
      payload: {
        currentYear: value,
      },
      callback: data => {
        self.props.getItems(self.props, match.params.project);
      },
    });
  }

  render() {
    const months = [
      {
        title: '年度合计',
        value: '14',
        key: '14',
      },
      {
        title: '全部月份',
        value: '13',
        key: '13',
        children: [
          { key: '1', value: '1', title: '1月' },
          { key: '2', value: '2', title: '2月' },
          { key: '3', value: '3', title: '3月' },
          { key: '4', value: '4', title: '4月' },
          { key: '5', value: '5', title: '5月' },
          { key: '6', value: '6', title: '6月' },
          { key: '7', value: '7', title: '7月' },
          { key: '8', value: '8', title: '8月' },
          { key: '9', value: '9', title: '9月' },
          { key: '10', value: '10', title: '10月' },
          { key: '11', value: '11', title: '11月' },
          { key: '12', value: '12', title: '12月' },
        ],
      },
    ];
    const { attributes, attributes1 } = this.state;
    const {
      attributesCheckeds,
      attributesCheckeds1,
      overAllYears,
      currentYear,
      currentMonths,
    } = this.props;
    return (
      <Fragment>
        {/* <div className={styles.entireProjectHeader}> */}
        <Row style={{ margin: '0 0 10px 0' }} type="flex" align="middle" justify="space-between">
          <Col>
            <Checkbox.Group
              onChange={this.props.onChangeAttributesCheckeds}
              options={attributes}
              defaultValue={attributesCheckeds}
            />
            &nbsp;&nbsp;
            {currentYear !== '' ? (
              <>
                <Select
                  // mode="multiple"
                  size="small"
                  style={{ width: 100 }}
                  placeholder="请选择"
                  value={currentYear}
                  onChange={e => this.changeCurrentYear(e)}
                >
                  {overAllYears &&
                    overAllYears.length > 0 &&
                    overAllYears.map(data => (
                      <Option key={data}>
                        {data}
                        {new Date().getFullYear().toString() === data.toString() ? '(今年)' : ''}
                      </Option>
                    ))}
                </Select>
                &nbsp;&nbsp;
                <TreeSelect
                  size="small"
                  style={{ width: 230 }}
                  value={currentMonths}
                  mode="multiple"
                  onChange={this.changeCurrentMonths}
                  treeCheckable
                  maxTagCount={2}
                  treeData={months}
                ></TreeSelect>
              </>
            ) : null}
          </Col>
          <Col>
            <AuthorizedButton authority="supply_overall_OkSupply">
              <Button type="primary" onClick={this.handleOkSupplyClick}>
                确认供货
              </Button>
            </AuthorizedButton>
            {/* <AuthorizedButton authority="supply_overall_exportReport">
              <Button className="yellow-button" onClick={this.handleExportReportClick}>
                导出报表
              </Button>
            </AuthorizedButton>
            <AuthorizedButton authority="supply_overall_versionComparison">
              <Button onClick={this.handleVersionComparisonClick}>版本对比</Button>
            </AuthorizedButton> */}
            &nbsp;&nbsp;
            <Button onClick={this.toggleForm}>
              高级筛选
              {<Icon type={this.state.expandForm ? 'up' : 'down'} />}
            </Button>
          </Col>
        </Row>
        {/* </div> */}
        <div className="header-search-area">
          {this.state.expandForm ? this.renderAdvancedForm() : null}
        </div>
      </Fragment>
    );
  }
}
